package managementnode

import (
	"zstackgo/pkg/core/componentloader"
	"zstackgo/pkg/core/rest"
	"zstackgo/pkg/core/thread"
	"zstackgo/pkg/tag"
	"zstackgo/spring"

	"github.com/go-spring/spring-core/gs"
)

var (
	parent gs.Container
)

type BootstrapContextLoaderListener struct{}

func (l *BootstrapContextLoaderListener) ContextInitialized() {
	if parent == nil {
		parent = spring.NewApplicationContext()
	}

	// new ClassPathXmlApplicationContext(configLocation)的逻辑:
	// 1. org.springframework.beans.factory.xml.XmlBeanDefinitionReader: Loading XML bean definitions即zstack.xml, 并执行入口函数refresh()
	// 1. org.springframework.beans.factory.xml.PluggableSchemaResolver: PluggableSchemaResolver Loading schema mappings from [META-INF/spring.schemas]
	// 1. org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver: Loading NamespaceHandler mappings from [META-INF/spring.handlers]. 即spring handler扩展机制, 实际执行了org.zstack.core.componentloader.PluginNameSpaceHandler
	// 1. org.springframework.beans.factory.xml.XmlBeanDefinitionReader逐个加载conf/springConfigXml/*.xml, 并对其bean进行处理, 包括用org.zstack.core.componentloader.PluginDefinitionParser处理其中的zstack bean插件`zstack:plugin`
	// 1. org.springframework.orm.jpa.persistenceunit.PersistenceUnitReader载入WEB-INF/classes/persistence.xml. 引入入口是springConfigXml/{DatabaseFacade, RESTFacade}.xml的`<property name="persistenceXmlLocation" value="persistence.xml"/>`
	// 1. hibernate处理persistenceXmlLocation
	// 1. org.springframework.beans.factory.support.DefaultListableBeanFactory: Creating shared instance of singleton bean并通过org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor完成Autowiring
	// 1. 结束标志: Root WebApplicationContext initialized
	new(componentloader.PluginNameSpaceHandler).Init()
	new(thread.ThreadFacadeImpl).Init() // conf/springConfigXml/ThreadFacade.xml声明ThreadFacadeImpl是特殊处理, 没找到位置???
	new(tag.TagManagerImpl).Init()
	new(rest.RESTFacadeImpl).Init()

	parent.Refresh()
}

func (l *BootstrapContextLoaderListener) ContextDestroyed() error {
	return nil
}
